<template>
  <div class="clearfix">
    <a-upload name="avatar"
              list-type="picture-card"
              class="avatar-uploader" :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload" @change="changoload">
      <a-button>
        <a-icon type="upload" />
        Select File
      </a-button>
    </a-upload>
    <a-button
      type="primary"
      :disabled="fileList.length === 0"
      :loading="uploading"
      style="margin-top: 16px"
      @click="handleUpload"
    >
      {{ uploading ? "Uploading" : "Start Upload" }}
    </a-button>
  </div>
</template>
<script>
// import reqwest from 'reqwest';
import api from "@/api/cloudStorage";
export default {
  data() {
    return {
      fileList: [],
      uploading: false,
      files:[],
      count:[],
    };
  },
  methods: {
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      this.fileList = [file];
      const reader = new FileReader();

      reader.readAsDataURL(file);
      reader.onload = e => {
        file.thumbUrl = e.target.result;
        this.files.push(file)
        this.files.map((item, index) => {
          if (file.name === item.name) {
            this.count.push(index);
            if (this.count.length > 1) {
              this.$message.error("文件已存在!");
              this.files.splice(index, 1);
              return;
            }
          }
        })
        this.fileList = [...this.files];

        // this.props.onChange(this.state.fileList)

      };
      return false;
    },
    changoload(file){
      console.log(file);
      this.$emit("input", file);
    },
    handleUpload() {
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append("files[]", file);
      });
      console.log('--------------------------');
      console.log(fileList);
      this.uploading = true;
      this.$emit("input", formData);

    }
  }
};
</script>
